package ReflectTest;

import ClassTest.Student;

import java.lang.reflect.Field;

/*
通过反射机制访问一个java对象的属性
    给属性赋值
    获取属性的值
 */
public class ReflectFieldTest3 {
    public static void main(String[] args) {
        try {
            Class student = Class.forName("ClassTest.Student");
            Object o = student.newInstance();
            //获取num属性(根据属性的名称来获取Field)
            Field field = student.getDeclaredField("num");
            //给o对象(Student对象)的num属性赋值
            field.set(o,"123");
            System.out.println(field.get(o));
            //访问私有属性，需要打破封装
            Field field1 = student.getDeclaredField("name");
            field1.setAccessible(true); //打破封装
            field1.set(o,"你好");
            System.out.println(field1.get(o));
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (NoSuchFieldException e) {
            e.printStackTrace();
        }
    }
}
